from flask import Blueprint,request,jsonify
import json
from database import *
from conf.comm import sqlalchemy_context

bp_cates = Blueprint('cates', __name__)



# 
def xtree(data):
    if data:
        tree = {}
        list = []
        # 根据id解析程字典
        for i in data:
            # id 作为key    i作为值
            tree[i['id']] = i
        for j in data:
            # 判断父id是否等于0  等于0则直接添加到列表里
            if j['parent'] ==0:
                list.append(j)
            else:
                # 如果son不在tree 字典里  则自己定义空字典  如果在 则直接添加
                if 'son' not in tree[j['parent']]:
                    tree[j['parent']]['son'] = []
                tree[j['parent']]['son'].append(j)
        return list
    else:
        return data
@bp_cates.route('/addclass/',methods=['POST','GET'])
@sqlalchemy_context()
# 添加分类接口
def addclass():
    if request.method =='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        
        # parent = ''
        # try:
        #     parent = data['parent']
        # except :
        #     parent = ''
        try:
            cate = Cate(name=data['name'],level=data['level'],params=data['params'],parent=data['parent'])
            db.session.add(cate)
            db.session.commit()
            return jsonify({'code':200,'mes':'添加成功'})
        except:
            return jsonify({'code':10031,'mes':'添加失败'})
    elif request.method == 'GET':
        # 获取所有数据
        cate = Cate.query.all()
        if cate:  # 如果存在遍历他
            list = []
            for i in cate:
                list.append({'id':i.id,'name':i.name,'level':i.level,'parent':i.parent,'params':i.params})
            list = xtree(list)
            return jsonify({'code':200,'list':list})
        else:
            return jsonify({'code':10032,'list':list})
    
import os
import uuid
# 课程上传
@bp_cates.route('/CateMarage/',methods=['POST','GET'])
@sqlalchemy_context()
def CateMarage():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.format()
        # print(uuidpic)
        cate = Course(name=data['name'],description=data['description'],tname=data['tname'],pic=data['pic'],vedios=data['vedios'],cid=data['cid'])
        db.session.add(cate)
        try:
            db.session.commit()
            return jsonify({"code":200,'msg':'上传成功'})
        except:
            return jsonify({"code":403,'msg':'上传失败'})
        
    elif request.method=='GET':
        # 获取id
        id = request.args.get('id')
        if id:
            course = Course.query.filter_by(id=id).first()
            onelist = {'id':course.id,'name':course.name,'description':course.description,'tname':course.tname,'pic':course.pic,'vedios':course.vedios,'cid':course.cid}
            print(onelist)
            return jsonify({"code":200,'onelist':onelist})
        # 当前页
        page =int(request.args.get('page'))
        #每页多少条
        size = int(request.args.get('size'))
        # 读取数据
        start = (page-1)*size
        course = Course.query.offset(start).limit(size)
        # 对结果进行解析
        list = []
        if course:
            for i in course:
                list.append({'id':i.id,'name':i.name,'pic':i.pic,"tname":i.tname,'description':i.description})
        # 共有多少条记录
        total = Course.query.count()
        return jsonify({"code":200,'list':list,'total':total})



